----- Khoa so 
DROP  PROCEDURE [dbo].[pr0365]
GO
CREATE  PROCEDURE [dbo].[pr0365] @DivisionID varchar(20), 
				@TranMonth as int, 
				@TranYear as int,
				@BeginDate as datetime,
				@EndDate as datetime
	
 AS


Declare @Closing As Bit,
	@NextMonth 	TinyInt,
	@NextYear 	Smallint,
	@PeriodNum 	TinyInt,
	@MaxPeriod	Int 
	
	
	Select 	@PeriodNum = PeriodNum
	From	tb0001
	If @PeriodNum Is Null 
		Set @PeriodNum = 12

	Set @NextMonth = @TranMonth % @PeriodNum + 1
	Set @NextYear = @TranYear + @TranMonth/@PeriodNum

	Select  	@Closing = Closing
	From 	tb0199
	Where 	DivisionID = @DivisionID And TranMonth = @TranMonth And TranYear = @TranYear
		
	Select 	@MaxPeriod = Max(TranMonth + TranYear * 100)
 	From	tb0199
	Where	DivisionID = @DivisionID

	If  @Closing <> 1 
	Begin
		
		
		Update 	tb0199
		Set 	Closing = 1
		From 	tb0199
		Where 	DivisionID = @DivisionID And TranMonth =@TranMonth And TranYear = @TranYear

		IF	@MaxPeriod < (@NextMonth + @NextYear * 100)
		Begin
			Insert    	tb0199  (TranMonth,TranYear, DivisionID,Closing, BeginDate, EndDate) 
			Values(@NextMonth,@NextYear, @DivisionID,0,@BeginDate, @EndDate)

			If Exists (Select 1 From tb0000 Where DefDivisionID = @DivisionID)
			Begin
				Update tb0000
				Set 	DefTranMonth = @NextMonth,
					DefTranYear = @NextYear			
			End

		/*
			Insert 	tb0106 	(InventoryID,WarehouseID,TranMonth,TranYear,DivisionID, InventoryAccountID,
						BeginQuantity, BeginAmount,
						DebitQuantity, DebitAmount,
						CreditQuantity, CreditAmount,
						EndQuantity, EndAmount, UnitPrice)
			Select 	InventoryID,WareHouseID,@NextMonth,@NextYear,DivisionID,  InventoryAccountID,
						EndQuantity, EndAmount,
						0,0,
						0,0,
						EndQuantity, EndAmount, UnitPrice
			From 	tb0106
			Where 	DivisionID = @DivisionID And 
				TranMonth = @TranMonth And 
				TranYear = @TranYear And 
				(Select Count(*)  From  tb0106 T8
					Where 	T8.TranMonth = @NextMonth And T8.TranYear = @NextYear And 
						T8.DivisionID = tb0106.DivisionID And 
						T8.InventoryID = tb0106.InventoryID And 
						T8.WareHouseID = tb0106.WareHouseID) = 0
		*/

		End
		
		IF	@MaxPeriod >= (@NextMonth + @NextYear * 100)
		Begin	
			Update 	tb0199
			Set 	BeginDate = @BeginDate,
				EndDate = @EndDate
			From 	tb0199
			Where 	DivisionID = @DivisionID And TranMonth = @NextMonth And TranYear = @NextYear
		end


		While    @MaxPeriod >= (@NextMonth + @NextYear * 100)
		Begin
			Exec  pr0364 @DivisionID, @TranMonth, @TranYear,@NextMonth , @NextYear
			Select   @TranMonth = @NextMonth, @TranYear = @NextYear
			Set @NextMonth = @TranMonth % @PeriodNum + 1
			Set @NextYear = @TranYear + @TranMonth/@PeriodNum			
		End

	
	End


GO